package com.wn.ziroom.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wn.ziroom.entity.Category;
import com.wn.ziroom.mapper.CategoryMapper;
import com.wn.ziroom.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wangzhijia
 * @since 2023-02-23 02:27:54
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    private CategoryMapper categoryMapper;

    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    public void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Autowired
    public void setCategoryMapper(CategoryMapper categoryMapper) {
        this.categoryMapper = categoryMapper;
    }

    @Override
    public List<Category> queryCategoryList() {
        HashOperations<String, Object, Object> opsForHash = stringRedisTemplate.opsForHash();
        Map<Object, Object> objectMap = opsForHash.entries("categoryList");

        if (objectMap.isEmpty()) {

            List<Category> categoryList = categoryMapper.selectList(null);
            HashMap<String, String> map = new HashMap<>();
            for (Category category : categoryList) {
                map.put(category.getCategoryId() + "", category.getCategoryName());
            }
            opsForHash.putAll("categoryList", map);
            return categoryList;
        }else {
            List<Category> list = new ArrayList<>();
            Set<Object> keySet = objectMap.keySet();

            for (Object o : keySet) {
                System.out.println("keySet:"+o);
            }

            for (Object o : keySet) {

                Integer cid = Integer.valueOf((String)o);

                Category category = new Category();

                String categoryName = (String) objectMap.get(o);
                category.setCategoryId(cid);
                category.setCategoryName(categoryName);
                list.add(category);
            }
            return list;
        }
    }
}
